<?php 
/* $querystring = parse_url('http://mp3.zing.vn/album/Dut-Tung-Doan-Ruot-Luong-Bich-Huu/ZWZAE6EA.html', PHP_URL_QUERY);
parse_str($querystring, $vars);
echo '<pre>';
print_r($vars);
echo '</pre>'; */

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	
	require_once 'libraries/function/validateAjax.php';

	
	$data = array();
	
	if($_GET['setNewAvatar'] == 1){
		$avatar = $_POST['newAvatar'];
		
		$tmpArray = explode('_', $avatar);
		$folder = $tmpArray[0] . '/' . $tmpArray[1] . '/' . $tmpArray[2] . '/';
		$agent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15';
		$url = IMAGE_URL . 'avatar/original/' . $folder . $avatar;
		$url = str_replace(" ", '%20', $url);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		$result = curl_exec($ch);
		
		
		if($result !== false){
			$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			echo $statusCode;
			if($statusCode != 200){
				exit();
			}else{
				$model = new model();
				$model->where = "id = '" . $_SESSION['user']['id'] . "'";
				$data = array('avatar' => $avatar);
				$model->update('users', $data);
				
				$resultdel = file_get_contents(
					R_IMAGE_URL . 'avatar.php?file=' . urlencode($_SESSION['user']['avatar']), 
					false, 
					stream_context_create(array(
				        'http' => array(
				            'method' => 'DELETE' 
				        )
				    ))
				);
		
				$_SESSION['user']['avatar'] = $avatar;
			}
		}
	}
	
	if($_GET['validateTitle'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
		}else{
			echo json_encode(array('errors'=>''));
			
		}
		exit();
		
	}

	if($_GET['validateDescription'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateDescription($_POST['txtDescription'], array( 'validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
		}else{
			echo json_encode(array('errors'=>''));
			
		}
		exit();
	}
	
	/*
	 *  Validate image form
	 */
	
	if($_GET['validatePostImage'] == 1){

		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		$validateAjax->validateFiles($_POST['uploadedFile']);
		
		
		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_image';
			$image = $_POST['uploadedFile'][0];
			unset($_POST['uploadedFile'][0]);
			
			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'				=> $_SESSION['user']['username'],
					'status'			=> 1,
			);
			$model->insert($table, $data);
			
			$model->select = "id";
			$model->where = "username = '" . $_SESSION['user']['username'] . "'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_image');
			$result = $model->fetchOne();
			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
									'post_id' => $result['id'],
									'image'		=> $file,
									'date_created'	=> $datetime
								);
						$model->insert('images', $fileData);
					}
				}
				
				$indexData = array(
							'post_id'	=> $result['id'],
							'is_image'	=> 1,
							'id_album'	=> $data['album_id'],
							'username'	=> $_SESSION['user']['username'],
							'status'	=> 1,
							'cat_id'	=> $_POST['txtCat']
						);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				
				
				
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}
	
	/*
	 *  Validate video post
	 */
	if($_GET['validatePostVideo'] == 1){
	
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));

		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		$video = $validateAjax->validateVideoSource($_POST['txtSourceUrl'], $_POST['txtSource']);

		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			
			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_media';
			$content = $video->getContent();

			//$image = $content['items'][0]['snippet']['thumbnails']['standard']['url'];
			
			$image = $video->getImage($content['items'][0]['snippet']['thumbnails']);

			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'media_type'		=> $video->_alias,
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'url'				=> $_POST['txtSourceUrl'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);

			$model->insert($table, $data);
				
			$model->select = "id, album_id";
			$model->where = "username = '".$_SESSION['user']['username']."'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_media');
			$result = $model->fetchOne();
			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);
						$model->insert('images', $fileData);
					}
				}
	
				$indexData = array(
						'post_id'	=> $result['id'],
						'is_video'	=> 1,
						'status'	=> 1,
						'id_album'	=> $result['album_id'],
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $_POST['txtCat']
				);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}
	
	
	if($_GET['validatePostText'] == 1){
	
	
		$validateAjax = new ValidateAjax();
		$validateAjax->validateMainImage($_POST['txtMainImage']);
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));

	
	
		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			
			$surl="content=".urlencode($_POST['txtDescription']);
			$url = IMAGE_URL . 'text/image.php';
			$resultContent = mycurl($surl,$url);
			$_POST['txtDescription'] = urldecode($resultContent);

			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_text';
			$image = $_POST['txtMainImage'];
			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);
			$model->insert($table, $data);
				
			$model->select = "id";
			$model->where = "username = '" . $_SESSION['user']['username'] . "'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_text');
			$result = $model->fetchOne();

			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);
						$model->insert('images', $fileData);
					}
				}
	
				$indexData = array(
						'post_id'	=> $result['id'],
						'is_text'	=> 1,
						'status'	=> 1,
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $_POST['txtCat'],
						'id_album'	=> $_POST['txtAlbum']
				);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}

	
	if($_GET['validateGetStory'] == 1){

		header("Cache-Control: no-cache, must-revalidate");
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả truyện'));
	
		//$validateAjax->validateCategory($_POST['txtCat']);
		//$validateAjax->validateAlbum($_POST['txtAlbum']);
		$story = $validateAjax->validateStorySource($_POST['txtSourceUrl'], $_POST['txtSource']);
		
		if($story instanceof sstruyen){
			$class = '1';
			$getlink_start = 0;
		}
		
		if($story instanceof webtruyen){
			$class = '2';
			$getlink_start = 1;
		}
		
		if($story instanceof tunghoanh){
			$class = '3';
			$getlink_start = 1;
		}
	
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			// Insert story to database
			$model = new Model();
			$dataInsert = array(
					'ten'	=>	$_POST['txtTitle'],
					'tacgia'	=> $_POST['txtAuthor'],
					'tongsochuong'	=> $_POST['txtChaptNums'],
					'gioithieu'	=> $_POST['txtDescription'],
					'time_upload'	=> date('Y-m-d H:i:s'),
					'user_upload'		=> 'millertime',
					'getlink_type'	=> $class,
					'getlink_source'	=> $_POST['txtSourceUrl'],
					'getlink_start'		=> $getlink_start,
					'getlink_auto'		=> $_POST['txtAutoScan'],
			);
			
			$model->insert('truyen', $dataInsert);
				
			//Select new story into select box
			$model->select = 'id';
			$model->where = "user_upload = 'millertime'";
			$model->order = "id DESC";
			$model->limit = "1";
			$model->getdata('truyen');
			$result = $model->fetchOne();
			$idStory = $result['id'];
				
			echo json_encode(array('message' => 'Tạo truyện thành công', 'url' => $story->patternUrl , 'startPage' => $story->startPage, 'story_id' => $idStory));
			exit();
		}
	}
	
	if($_GET['validateGetChapter'] == 1){
		
		$story = storyfactory::create($_POST['txtSource']);
		$returnLinks = $story->getChapters($_POST['txtSourceUrl']);

		if($returnLinks == 'het'){
			echo 'het';
		}else if(is_array($returnLinks)){
			$a = json_encode($returnLinks);
			echo $a;
		}else{
			echo 'Not specific';
		}
		exit();
	}
	
	if($_GET['insertChapter'] == 1){

		$links = json_decode($_POST['links'],true);

		$storyData = $_POST['storyData'];

		$model = new Model();

		foreach($links as $key => $value){
			if($value['title'] == 'Error' || $value['href'] == 'Error'){
				$is_finish = 0;
			}else{
				$is_finish = 1;
			}
			
			$dataInsert = array(
					'link' => $value['link'], 
					'title' => $value['title'], 
					'story_id' => $storyData['story_id'], 
					'page'=>$storyData['startPage'],
					'thutu'=>$value['chapt'],
					'tap'=>$value['tap'],
					'is_finish'	=> $is_finish,
			);
			
		
			
			$model->insert('truyen_chuong_link', $dataInsert);
			
			if(!$links[$key + 1]){
				$model->where = "id = '" . $storyData['story_id'] . "'";
				$dataLast = array('getlink_last'=>$value['link'], 'getlink_page'=>$storyData['startPage']);
				$model->update('truyen', $dataLast);
			}
		}
		//echo 'here';
		exit();
	}
	
	if($_GET['submitStoryChapters'] == 1){

		$story = $_POST['story_id'];
		if(!isset($story) || empty($story)){
			echo json_encode(array('error'=>'Nhập truyện cần lấy nội dung!!!'));
		}
		
		$model = new Model();
		$model->select = '*';
		$model->where = "id = '" . $story . "'";
		$model->getdata('truyen');
		$result = $model->fetchOne();
		if(!$result){
			echo json_encode(array('error'=>'Truyện không tồn tại nhé'));
			
			
		}
		
		$model->select = "*";
		$model->where = "story_id ='" . $result['id'] . "' AND get_content = 0";
		$model->getdata('truyen_chuong_link');
		$resultChapters = $model->fetchAll();
		if(!$resultChapters){
			echo json_encode(array('error'=>'Không có link để lấy nội dung.'));
		}

		$story = storyfactory::create($result['getlink_type']);


		foreach($resultChapters as $key => $value){

			$contentChapter = $story->getChapterContent($value['link']);
			
			$pos = strpos($contentChapter, '<img');
			if($pos !== false){
				$is_image = true;
			}else{
				$is_image = false;
			}
			
			if(!$contentChapter){
				$errorChapters[] = $value['id'];
				$dataContent = array(
					'ten'=>$value['title'],
					'noidung'=>'',
					'thutu'=> $value['thutu'],
					'trangthai'	=> 0,
					'truyen_id' => $value['story_id'],
					'image'	=> '0',
					'truyen_chuong_link_id'	=> $value['id']
					);
			}
			
			$dataContent = array(
					'ten'=>$value['title'],
					//'noidung'=>$contentChapter,
					'thutu'=> $value['thutu'],
					'trangthai'	=> 1,
					'truyen_id' => $value['story_id'],
					'image'	=> $is_image,
					'truyen_chuong_link_id'	=> $value['id'],
					
					);
			
			$model->insert('truyen_chuong', $dataContent);
			
			$model->select = "id";
			$model->where = "truyen_id = '" . $value['story_id'] . "'";
			$model->order = "id DESC";
			$model->limit = "1";
			$model->getdata('truyen_chuong');
			$resultLastId = $model->fetchOne();
			
			if($resultLastId){
				$dataNoiDung = array('noidung'=> $contentChapter, 'truyen_chuong_id' => $resultLastId['id']);
				$model->insert('truyen_chuong_noidung', $dataNoiDung);
			}
			
			$dataChaptersLink = array('is_finish' => 1, 'image'	=> $is_image, 'get_content'=>1);
			$model->where = "id = '" . $value['id'] . "'";
			$model->update('truyen_chuong_link', $dataChaptersLink);
		}
		
		if($errorChapters){
			echo json_encode(array('error'=>'Một số chapter không lấy được nội dung.', 'fail_chapers'=>$errorChapters));
			exit();
		}
		
		echo '1';
	}
	
	
	
	if($_GET['getStories'] == 1){

		if($_POST['submitScan'] == 1){
			$model = new Model();
			$model->select = '*';
			$model->where = "getlink_auto = 1";
			$model->order = 'ten ASC';
			$model->getdata('truyen');
			$resultStories = $model->fetchAll();

			if($resultStories){
				
				foreach($resultStories as $key => $value){
					$story = storyfactory::create($value['getlink_type']);
					if($story instanceof sstruyen){
						$resultStories[$key]['pattern_url'] = preg_replace('/.html/', '/page-%s%.html#chaplist', $value['getlink_source']);
					}
					
					if($story instanceof webtruyen){
						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';
					}
					
					if($story instanceof tunghoanh){
						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';
					}
				}
				echo json_encode($resultStories);
				exit();
			}else{
				echo '0';
			}
		}
	}
	
	if($_GET['autoScanLinks'] == 1){
		
		if(!$_POST['dataStory']){
			echo 'error_story';
			exit();
		}else{
			$dataStory = $_POST['dataStory'];
			$story = storyfactory::create($dataStory['getlink_type']);
			//$returnLinks = $story->getChapters($_POST['txtSourceUrl']);
			$returnAutoChapters = $story->autoGetChapters($dataStory);

			if($returnAutoChapters == 'het'){
				echo 'het';
			}else if(is_array($returnAutoChapters)){
				$a = json_encode($returnAutoChapters);
				echo $a;
			}else{
				echo 'Not specific';
			}
			exit();
			
		}
		
		exit();
		
		$model = new Model();
		$model->select = '*';
		$model->where = "story_id = '" . $dataStory['id'] . "'";
		//$model->where
	}

}




